<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JS-Corner-03 Canvas</title>
</head>
<style>
    body{
        background:#FFF;
        text-align:center;
    }
    #c1{
        color:#fff;
    }
</style>
<body>
    本页面不需要启动服务器

    <h1>Canvas 实现游戏动效：人物走动</h1>

    <canvas id="c1" width="500" height="500"></canvas>

    <script>
        // Canvas
        //    width: 500
        //    height: 500
        // walk.jpg
        //    width: 100*4(actions)       400
        //    height: 210*4(directions)   840

        window.onload = function(){
            let oC = document.getElementById('c1')
            let gd = oC.getContext('2d')

            let direction = 'Left'

            let i=0     // walk-range:0-3
            let j=0     // 0:down 1:left 2:right 3:up
            let x = 100 // init-position:x
            let y = 100 // init-position:y
            let frameCounter = 0    // refresh-rate

            let oImg = new Image()
            oImg.src = 'walk.jpg'
            oImg.onload = function(){
                requestAnimationFrame(next)
            }

            function next(){
                gd.clearRect(0,0,oC.width, oC.height)
                gd.strokeStyle='red'
                gd.strokeRect(0,0,500,500)

                gd.drawImage(
                    oImg,
                    i*100,j*210,100,210,
                    x,y,100,210
                )
                
                if(frameCounter % 5 === 0){
                    i++
                    if(i==4) i=0;
                    frameCounter=0
                }
                frameCounter++
            }

            document.onkeydown = function(event){

                switch(event.keyCode){
                    case 37:    // Left
                        x-=2
                        j=1
                        break;
                    case 38:    // Up
                        y-=2
                        j=3
                        break;
                    case 39:    // Right
                        x+=2
                        j=2
                        break;
                    case 40:    // Down
                        y+=2
                        j=0
                        break;
                }

                // walk-range-control
                if(x >= 400){
                    x = 390
                }
                if(x<=0){
                    x = 10
                }
                if(y<=0){
                    y=10
                }
                if(y>=290){
                    y=280
                }

                // refresh
                requestAnimationFrame(next)
            }

        }
    </script>
</body>
</html>